﻿using System;

class FindIndexByBinarySearch

            // Write a program that finds the index of given element in a sorted array of integers by using the binary search algorithm (find it in Wikipedia).

{
    static int binSearch(int[] array, int getIndex)
    {
        int min = 0;
        int max = array.Length - 1;
        while (max >= min)
        {
            int mid = (max + min) / 2;
            if (array[mid] < getIndex)
            {
                min = mid + 1;
            }
            else if (array[mid] > getIndex)
            {
                max = mid - 1;
            }
            else
            {
                return mid;
            }
        }
        return -1;
    }
 
    static void Main()
    {
        Console.Write("Enter the length of the array: ");
        int arraySize = int.Parse(Console.ReadLine());
        int[] array = new int[arraySize];
        Console.Write("Enter the number to be searched for: ");
        int number = int.Parse(Console.ReadLine());
        Console.WriteLine();

        Console.WriteLine("Enter the elements of the array:");
        for (int i = 0; i < arraySize; i++)
        {
            array[i] = int.Parse(Console.ReadLine());
        }
        if (binSearch(array, number) == -1)
        {
            Console.WriteLine("The number {0} could not be found in the array!", number);
        }
        else
        {
            Console.WriteLine("The index of the number searched is: " + binSearch(array, number));
        }
    }
}

